const router = require('koa-router')();
const validator = require('validator');
const {getTree} = require('../../module/tools');

router.prefix('/classification');

router.get('/', async ctx => {
  ctx.redirect('/admin/classification/index')
});

/**
 * 分类列表
 */
router.get('/index', async ctx => {
  const list = await ctx.state.DB.find('classification');
  const tree = getTree(list);
  ctx.render('admin/classification/index', {
    tree
  })
});

/**
 * 增加分类页面
 */
router.get('/add', async ctx => {
  const parentList = await ctx.state.DB.find('classification', {pid: '0'});
  console.log(parentList);
  await ctx.render('admin/classification/add', {parentList})
});

/**
 * 执行增加分类
 */
router.post('/doAdd', async ctx => {
  let params = ctx.request.body;
  if (validator.isEmpty(params.title) || validator.isEmpty(params.pid) || validator.isEmpty(params.status)) {
    ctx.body = {code: -1, msg: '请完善信息'};
  } else {
    try {
      params = {
        ...params,
        status: (params.status === 'true')
      };
      await ctx.state.DB.insert('classification', params);
      ctx.redirect('/admin/classification/index')
    } catch (e) {
      ctx.body = {code: -1, msg: '增加分类失败'};
    }
  }
});

/**
 * 编辑分类页面
 */
router.get('/edit', async ctx => {
  const parentList = await ctx.state.DB.find('classification', {pid: '0'});
  const data = await ctx.state.DB.find('classification', {_id: ctx.state.DB.getObjId(ctx.query.id)});
  await ctx.render('admin/classification/edit', {
    ...data[0],
    parentList
  });
});

/**
 * 执行编辑分类
 */
router.post('/doEdit', async ctx => {
  const params = ctx.request.body;
  // console.log(params);
  try {
    await ctx.state.DB.update('classification', {_id: ctx.state.DB.getObjId(params._id)}, {
      title: params.title,
      pid: params.pid,
      keywords: params.keywords,
      status: (params.status === 'true'),
      description: params.description
    });
    ctx.redirect('/admin/classification/index')
  } catch (e) {
    ctx.body = {code: -1, msg: '编辑用户失败'};
  }
});

module.exports = router;